<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2016/8/11
 * Time: 14:01
 */
namespace YMApi\Model;
use SDXApi\Repositories\BuyNowGoodsRepository;
use SDXApi\Service\BuyNowGoodsService;
use SDXApi\Service\PromoteService;
use Think\Model;

class NewCartModel extends Model
{
    protected $tableName = 'cart';


    public function uid_favourable_list($uid){
        //获取当前用户等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        $now = gmtime();

        $map = array();

        $map["start_time"] = array('elt',$now);
        $map["end_time"] = array('egt',$now);
        $map['act_type'] = array('in',array(FAT_GOODS,FAT_PRICE,FAT_DISCOUNT));
        $map['_string'] = "FIND_IN_SET(".$user_rank.", user_rank)";

        //获取当前用户可参与的活动（除抢购外）
        $favourable_activity_list = M('favourable_activity')->where($map)->select();
        return $favourable_activity_list;

    }

    /**
     * 获取购物车商品
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param array $favourable_list
     * @param int $flow_type
     * @param bool $refresh
     * @return array
     */
    public function get_cart_goods($uid,$wid,$rec_ids=0,$favourable_list=array(),$flow_type=CART_GENERAL_GOODS,$refresh=0){
        $cart_goods = $this->get_cart_goods_by_uid($uid,$wid,$rec_ids,$flow_type);
        //是否检查更新购物车商品价格
        if($refresh){
            $this->check_goods_price($cart_goods,$uid,false);
            $cart_goods = $this->get_cart_goods_by_uid($uid,$wid,$rec_ids,$flow_type);
        }
        $res = array();
        if(!empty($cart_goods)){
            //处理购物车中的商品活动数据
            //目前采购端不参加活动
            //$cart_goods = $this->convert_cart_goods($cart_goods, $favourable_list,true);

            //计算购物车金额以及优惠
            $res = $this->get_cart_total($cart_goods,$favourable_list,true);
        }

    	return $res;
    }


    /**
     * 获取用户购物车商品
     * @param $uid
     * @param $wid
     * @param int $rec_ids
     * @param int $flow_type
     * @return mixed
     */
    public function get_cart_goods_by_uid($uid,$wid,$rec_ids=0,$flow_type=CART_GENERAL_GOODS){
        $map = array();
        if($rec_ids){
            $map['c.rec_id'] = array('in',$rec_ids);
        }

        $user_rank = M("users")->where(array("user_id"=>$uid))->getField("user_rank");

        $map['c.user_id'] = $uid;
        $map['c.rec_type'] = $flow_type;
        $map['g.is_offline'] = 0;	//排除线下销售商品

        $cart = D('cart');
        $cart_goods = $cart->alias("c")
            ->field("c.*,IF(c.parent_id, c.parent_id, c.goods_id) AS pid,g.cat_id,g.brand_id,g.goods_weight,g.spec_value,g.spec_unit,g.is_presell,g.delivery_type,g.delivery_cycle,g.min_buy_num,g.goods_number as goods_stock,g.goods_thumb,g.goods_img,g.goods_brief,g.is_on_sale,g.promote_price,g.promote_end_date,g.promote_start_date,g.practical_num,g.is_auto_morrow_presell,g.is_buynow, g.promote_goods_number, g.promote_today_number")
            ->join("left join ".C('DB_PREFIX')."goods_wid_".$wid." g on c.goods_id=g.goods_id")
            ->where($map)
            ->group("c.rec_id")
            ->order("c.giving asc,c.rec_id desc")
            ->select();
        //dump($cart_goods);
        foreach ($cart_goods as $key=>$value){
            $cart_goods[$key]['goods_price'] = M("supply_price")->where(array("goods_id"=>$value['goods_id'],"user_rank"=>$user_rank))->getField("user_price");
            $cart_goods[$key]['shop_price'] = M("supply_price")->where(array("goods_id"=>$value['goods_id'],"user_rank"=>1))->getField("user_price");
            $cart_goods[$key]['vip_price'] = M("supply_price")->where(array("goods_id"=>$value['goods_id'],"user_rank"=>2))->getField("user_price");
        }

        return $cart_goods;
    }

    /*
     * 普通商品购物车价格变动检查
     */
    private function check_normal_price($goods,$uid,$user_rank){
        $result = array('have_change'=>0);
        $map = array();
        $spec = "";
        if($goods['goods_attr_id']){
            $spec = explode(',', $goods['goods_attr_id']);
        }
        $goods_price = D('Goods')->get_final_price($goods['goods_id'], $goods['goods_number'], true, $spec, $uid);
        if($goods_price-$goods['goods_price']!=0){
            M('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
            $goods['new_goods_price'] = $goods_price;
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }


    /**
     * 活动商品购物车价格变动检查
     * @param array $goods 商品信息
     * @param int $user_rank 会员等级ID
     * @param array $act_list 用户可参考的活动
     * @param string $act_type 活动类型
     */
    public function check_giving_price($goods,$user_rank,$act_list,$act_type){
        $result = array('have_change'=>0);
        $act_info=$this->get_activityinfo($goods['act_id'], $act_list);
        if($act_type=='giving'){
            $serarr=unserialize($act_info['gift']);
        }else if($act_type=='quota'){
            $serarr=unserialize($act_info['quota']);
        }
        foreach($serarr as $item){
            $goods_id_list[]=$item['id'];
            $goods_price_list[]=$item['price'];
            $goods_list[$item['id']]=$item['price'];
        }
        if(($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext']) && $goods_list[$goods['id']]!=$goods['goods_price']))){
            $goods['new_goods_price'] = $goods_list[$goods['id']];
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }


    /**
     * 取得购物车商品
     * @param   int     $type   类型：默认普通商品
     * @return  array   购物车商品数组
     */
    public function cart_goods($type = CART_GENERAL_GOODS,$rec_ids='',$uid=0,$wid=0) {
        $where = array("user_id"=>$uid,"rec_type"=>$type);
        if(!empty($rec_ids)){
            $where['rec_id'] = array('in',$rec_ids);
        }

        $arr = M("cart")->field("*,goods_price*goods_number AS subtotal")->where($where)->select();
        /* 格式化价格及礼包商品 */
        foreach ($arr as $key => $value) {
            $arr[$key]['formated_market_price'] = price_format($value['market_price'], false);
            $arr[$key]['formated_goods_price'] = price_format($value['goods_price'], false);
            $arr[$key]['formated_subtotal'] = price_format($value['subtotal'], false);
            if ($value['extension_code'] == 'package_buy') {
                $arr[$key]['package_goods_list'] = $this->get_package_goods($value['goods_id']);
            }
            //             $arr[$key]['goods_total_price'] = $value['goods_price']*$value['goods_number'];
            $arr[$key]['goods_total_price'] = $value['subtotal'];

            $goods = D('goods')->where(array('goods_id'=>$value['goods_id']))->find();
            $arr[$key]['goods_img'] = img_init($goods['goods_img']);
            $arr[$key]['is_auto_morrow_presell'] = $goods['is_auto_morrow_presell'];
            $arr[$key]['virtual_goods_number'] = $goods['goods_number'];
            $is_presell=$goods['is_presell'];
            $goods['is_presell']=(int)$goods['is_presell'];
            if($goods['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $is_presell=D('Goodsstorage')->check_whether_presell($goods['goods_id'],$wid);
            }
            if($is_presell){
                $arr[$key]['is_presell']=1;
                $arr[$key]['goods_stock'] =  $goods['goods_number'];
                if($goods['delivery_type']==1){  //分段发货
                    $Goodspreselltime=D('Goodspreselltime');
                    if($Goodspreselltime->check_shipping_goodspreselltime($goods['goods_id'])){//检查预售商品是否设置发货配送时间
                        $preselltimeres=$Goodspreselltime->check_shippingtime($goods['goods_id'],time());
                        if($preselltimeres){
                            $arr[$key]['preselltimeres']=$preselltimeres;
                        }else{
                            $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                        }
                    }else{
                        $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                    }
                }elseif($goods['delivery_type']==2){ //定时方式
                    if($goods['delivery_cycle']){
                        $gmd=local_date('Y-m-d',gmtime());
                        $goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$goods['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
                        $arr[$key]['preselltimeres']=array('delivery_time'=>$goods_presell_time);
                    }else{
                        $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                    }
                }else{
                    $arr[$key]['preselltimeres']=array('delivery_time'=>'');
                }

            }else{
                $arr[$key]['is_presell']=0;
                $goodsstorage=D('Goodsstorage')->get_warehous_goods($wid,$goods['goods_id']);
                if($goodsstorage){
                    $arr[$key]['goods_stock']=$goodsstorage['practical_num'];
                }else{
                    $arr[$key]['goods_stock']=0;
                }
                $arr[$key]['preselltimeres']=array('delivery_time'=>'');
            }

            //如果商品名有变动，则修改购物车中的商品名
            if($arr[$key]['goods_name']!=$goods['goods_name']){
                $arr[$key]['goods_name'] = $goods['goods_name'];
                M('cart')->where(array('rec_id'=>$value['rec_id']))->setField('goods_name',$goods['goods_name']);
            }

        }

        return $arr;
    }


    /**
     * 购物车数据统计
     * @param $cart_goods
     * @param $favourable_list
     * @param bool $flag    否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function get_cart_total($cart_goods,$favourable_list,$flag=false){
    	$goods_list = array();
    	$goods_outstock_list = array();
    	$goods_list_total = array(
    			'goods_price' => 0, // 本店售价合计（有格式）
    			'market_price' => 0, // 市场售价合计（有格式）
    			'saving' => 0, // 节省金额（有格式）
    			'save_rate' => 0, // 节省百分比
    			'goods_amount' => 0, // 本店售价合计（无格式）
    			'total_number' => 0,
                'total_vip_price' =>0,
    	        'cart_total_number' =>0,
    	        'cart_total_amount' =>0
    	);
    	$goods_outstock_list_total = array(
    			'goods_price' => 0, // 本店售价合计（有格式）
    			'market_price' => 0, // 市场售价合计（有格式）
    			'saving' => 0, // 节省金额（有格式）
    			'save_rate' => 0, // 节省百分比
    			'goods_amount' => 0, // 本店售价合计（无格式）
    			'total_number' => 0,
                'total_vip_price' =>0
    	);

    	$cart = D('cart');
    	$goodsModel = D('Goods');
    	/* 用于统计购物车中实体商品和虚拟商品的个数 */
    	$virtual_goods_count = 0;
    	$real_goods_count = 0;
    	$out_stock_real_goods_count = 0;
    	$out_stock_virtual_goods_count = 0;

    	foreach ($cart_goods as $key=>$row) {
//    		dd($row);

    		/* 查询规格 */
    		if (trim($row['goods_attr']) != '') {
    			$row['goods_attr'] = addslashes($row['goods_attr']);
    			$attr_list = D('goods_attr')->field("attr_value")->where(array('goods_attr_id'=>array("in",$row['goods_attr_id'])))->select();
    			foreach ($attr_list as $key=>$attr) {
    				$row['goods_name'] .= ' [' . $attr['attr_value'] . '] ';
    			}
    		}
    		$row['goods_thumb'] = img_init($row['goods_img']);

    		/**
    		 * 判断促销价格是否已过期，过期后则自动获取商品最新价格
    		*/
    		//检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
            if($row['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                if($row['practical_num']>0){
                    $row['is_presell'] = 0;
                }else{
                    $row['is_presell'] = 1;
                }
            }

    		if($row['is_presell']){
    			if($row['delivery_type']==1){//分段发货
    				$Goodspreselltime=D('Goodspreselltime');
    				if($Goodspreselltime->check_shipping_goodspreselltime($row['goods_id'])){//检查预售商品是否设置发货配送时间
    					$preselltimeres=$Goodspreselltime->check_shippingtime($row['goods_id'],time());
    					if($preselltimeres){
    						$row['preselltimeres']=array('delivery_time'=>$preselltimeres['delivery_time']);
    					}else{
    						$row['preselltimeres']=array('delivery_time'=>'');
    					}
    				}else{
    					$row['preselltimeres']=array('delivery_time'=>'');
    				}
    			}elseif($row['delivery_type']==2){ //定时方式
    				if($row['delivery_cycle']){
    					$gmd=local_date('Y-m-d',gmtime());
    					$goods_presell_time = local_date('Y-m-d H:i:s', local_strtotime($gmd.' +'.$row['delivery_cycle'].' day '.C('DEFAULT_PRESELL_TIME_H')));
    					$row['preselltimeres']=array('delivery_time'=>$goods_presell_time);
    				}else{
    					$row['preselltimeres']=array('delivery_time'=>'');
    				}
    			}else{
    				$row['preselltimeres']=array('delivery_time'=>'');
    			}
    		}else{

    			if($row['practical_num']){
    				$row['goods_stock']=$row['practical_num'];
    			}else{
    				$row['goods_stock']=0;
    			}

    			$row['preselltimeres']=array('delivery_time'=>'');
    		}


    		$supply_discount = M("goods")->where(array("goods_id"=>$row['goods_id']))->getField("supply_discount");
            $now_discount = 1;//默认无折扣
    		if(!empty($supply_discount)){
    		    $supply_discount_list = array();
                $supply_discount = unserialize($supply_discount);
                foreach ($supply_discount as $supply_key=>$supply_vaule){
                    if($supply_vaule["base"]<=$row['goods_number']){
                        $supply_discount_list[$supply_vaule["base"]]=$supply_vaule["discount"];
                    }
                }
                if(count($supply_discount_list)>0){
                    $now_discount = end($supply_discount_list)/100;
                }
            }

            $row['subtotal'] = price_format($row['goods_price'] * $row['goods_number']*$now_discount, false);



    		//如果添加到购物车的数量大于库存，则修改为库存数量
    		if($row['goods_number']>$row['goods_stock'] && $row['goods_stock']>0 && $row['giving']==0){
    			$flag = $cart->where(array('rec_id'=>$row['rec_id']))->setField('goods_number',$row['goods_stock']);
    			if($flag!==false){
    				$row['goods_number'] = $row['goods_stock'];
    			}
    		}

    		if($row['spec_value']){
    			$row['spec_value'] =  $row['spec_value'];
    			$row['spec_unit'] =  $row['spec_unit'];
    		}elseif($row['goods_weight']){
    			$row['spec_value'] =  $row['goods_weight']*1000;
    			$row['spec_unit'] =  "g";
    		}
            $row['vip_price'] = get_price($row['vip_price']*$now_discount);
            $row['true_vip_price'] = get_price($row['vip_price']*$now_discount);
            $row['goods_price'] = $row['goods_price'] * $now_discount;
            $row['market_price'] = $row['market_price'] * $now_discount;
            $row['shop_price'] = $row['shop_price'] * $now_discount;
            $current_time = gmtime();
    		//拆分购物车中有库存与无库存商品
    		if($row['goods_stock']>0 && $row['is_on_sale']>0 && $row['is_delete']==0){
    			/* 统计实体商品和虚拟商品的个数 */

                if($row['is_check']==1){
                    if ($row['is_real']) {
                        $real_goods_count++;
                    } else {
                        $virtual_goods_count++;
                    }

//                    if (floatval($row['goods_price']) <= 0) {
//                    	$row['goods_price'] = $row['shop_price'];
//					}

                    $goods_list_total['total_number']+=$row['goods_number'];
                    $goods_list_total['goods_price'] += $row['goods_price'] * $row['goods_number'];
                    $goods_list_total['market_price'] += $row['market_price'] * $row['goods_number'];
                    $goods_list_total['shop_price'] += $row['shop_price'] * $row['goods_number'];
                    $goods_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number'];

                }

                $goods_list_total['cart_total_number']+=$row['goods_number'];
                $goods_list_total['cart_total_amount'] += $row['goods_price']*$row['goods_number'];
                $row['promote_price'] = 0;//无促销价格
    			$goods_list[] = $row;

    		}else{
    			/* 统计缺货或者已下架实体商品和虚拟商品的个数 */
    			if ($row['is_real']) {
    				$out_stock_real_goods_count++;
    			} else {
    				$out_stock_virtual_goods_count++;
    			}

//				if (floatval($row['goods_price']) <= 0) {
//					$row['goods_price'] = $row['shop_price'];
//				}

    			$goods_outstock_list_total['total_number']+=$row['goods_number'];
    			$goods_outstock_list_total['goods_price'] += $row['goods_price'] * $row['goods_number']*$now_discount;
    			$goods_outstock_list_total['market_price'] += $row['market_price'] * $row['goods_number']*$now_discount;
    			$goods_outstock_list_total['shop_price'] += $row['shop_price'] * $row['goods_number']*$now_discount;
                $goods_outstock_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number']*$now_discount;
                $goods_outstock_list_total['total_vip_price'] += $row['vip_price'] * $row['goods_number']*$now_discount;
                $row['promote_price'] = 0;//无促销价格
                $goods_outstock_list[] = $row;
    		}
    	}


    	//统计购物车有货商品数量以及金额
    	$goods_list_total['goods_amount'] = $goods_list_total['goods_price'];
        $goods_list_total['goods_price'] =  get_price($goods_list_total['goods_price']);
    	$goods_list_total['goods_price_format'] = price_format($goods_list_total['goods_price'], false);
    	$goods_list_total['market_price_format'] = price_format($goods_list_total['market_price'], false);
    	$goods_list_total['real_goods_count'] = $real_goods_count;
    	$goods_list_total['virtual_goods_count'] = $virtual_goods_count;


    	//统计购物车中缺货商品数量以及金额
    	$goods_outstock_list_total['goods_amount'] = $goods_outstock_list_total['goods_price'];
    	$goods_outstock_list_total['saving_format'] = price_format($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price'], false);
    	if ($goods_outstock_list_total['market_price'] > 0) {
    		$goods_outstock_list_total['save_rate'] = $goods_outstock_list_total['market_price'] ? round(($goods_outstock_list_total['market_price'] - $goods_outstock_list_total['goods_price']) *
    				100 / $goods_outstock_list_total['market_price']) . '%' : 0;
    	}
    	$goods_outstock_list_total['goods_price_format'] = price_format($goods_outstock_list_total['goods_price'], false);
    	$goods_outstock_list_total['market_price_format'] = price_format($goods_outstock_list_total['market_price'], false);
    	$goods_outstock_list_total['real_goods_count'] = $out_stock_real_goods_count;
    	$goods_outstock_list_total['virtual_goods_count'] = $out_stock_virtual_goods_count;


        //购物车中有货商品活动分组以及统计金额
    	$goods_total = $this->activity_goods_group($goods_list, $goods_list_total, $favourable_list,$flag);

    	return array('goods_list' => $goods_total['goods_list'], 'total' => $goods_total['total'], 'goods_outstock_list'=>$goods_outstock_list,'out_stock_total'=>$goods_outstock_list_total);
    }

	/**
	 * 购物车促销价过期与生效处理
	 * Created by Jerry
	 * @param $carData
	 * @return mixed
	 */
	protected function check_promote_price_by_time($carData)
	{
		$goodsModel = D('Goods');
		$carModel = M('Cart');

		$goodsWhere = array(
			'user_id'	=>	array('EQ', $carData['user_id']),
			'rec_id'	=>	array('EQ', $carData['rec_id']),
			'goods_id'	=>	array('EQ', $carData['goods_id']),
		);
		$goodsInfo = $goodsModel->field('promote_goods_number, promote_today_number')->where($goodsWhere)->find();

		$promote_price = bargain_price($carData['promote_price'], $carData['promote_start_date'], $carData['promote_end_date']);

		if ($promote_price > 0 && $carData['giving'] == 0 && $carData['goods_number'] <= $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0) {
//			促销价生效购物车价格未更改
			$saveData = array(
				'goods_price' 	=>	$promote_price,
				'giving'		=>	4,
			);

			$carModel->where($goodsWhere)->save($saveData);
			$carData['goods_price'] = $promote_price;
			$carData['giving'] = 4;
		}
		else if (($promote_price > 0 && $carData['giving'] != 4 && $carData['goods_number'] > $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0) || ($promote_price > 0 && $carData['giving'] == 4 && $carData['goods_number'] > $goodsInfo['promote_goods_number'] && $goodsInfo['promote_goods_number'] > 0))
		{
			//			促销价生效购物车价格未更改并超过限购数量
			$saveData = array(
				'goods_price' 	=>	$promote_price,
				'giving'		=>	4,
				'goods_number'	=>	$goodsInfo['promote_goods_number'],
			);

			$carModel->where($goodsWhere)->save($saveData);
			$carData['goods_price'] = $promote_price;
			$carData['giving'] = 4;
			$carData['goods_number'] = $goodsInfo['promote_goods_number'];
		}
		else if ($promote_price == 0 && $carData['giving'] == 4)
		{
//			促销价失效购物车未更改
			$price = $goodsModel->get_final_price($carData['goods_id'], 1, false, array(), $carData['user_id']);
			$saveData = array(
				'goods_price' 	=>	$price,
				'giving'		=>	0,
			);

			$carModel->where($goodsWhere)->save($saveData);
			$carData['goods_price'] = $price;
			$carData['giving'] = 0;
			$carData['promote_price'] = 0;
			$carData['promote_end_date'] = '';
			$carData['promote_start_date'] = '';
		}
		else if ($promote_price == 0 || ($promote_price == 0 && $carData['giving'] == 0))
		{
			$carData['promote_price'] = 0;
			$carData['promote_end_date'] = '';
			$carData['promote_start_date'] = '';
		}

		return $carData;
	}


    /**
     * 商品数据分组
     * @param $goods_list   商品列表
     * @param $total    商品统计数据
     * @param $favourable_list  活动列表
     * @param bool $flag  是否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function activity_goods_group($goods_list,$total,$favourable_list,$flag=false){
        $favourable_goods = array();
    	$normal_goods = array();
    	foreach ($goods_list as $key=>$goods){
    		if($goods['act_id']>0){
    			$activity = $this->get_activityinfo($goods['act_id'], $favourable_list);
    			if(!$activity){
    				$normal_goods[] = $goods;
    			}else{
    				$favourable_goods[$goods['act_id']]['info'] = $activity;
    				$favourable_goods[$goods['act_id']]['goods_list'][] = $goods;
    			}
    		}else{
    			$normal_goods[] = $goods;
    		}
    	}

    	$cart_goods_list = array();
        $cart_goods_list['favourable_goods'] = $this->get_activity_group_info($favourable_goods,$flag);
        $cart_goods_list['normal_goods'] = $normal_goods;

    	$data = array();
    	$data['goods_list'] = $cart_goods_list;
    	//计算加入满减，折扣后的金额
    	$data['total'] = $this->calculation_amount($total, $cart_goods_list['favourable_goods']);

    	return $data;
    }

    /**
     * 统计购物车金额
     * @param $total
     * @param $activity_goods_info
     * @return mixed
     */
    public function calculation_amount($total,$activity_goods_info){
    	$discount = 0;

    	foreach($activity_goods_info as $act_info){
    		$discount+=$act_info['info']['discount'];
    	}
    	$total['discount'] = get_price($discount);
        $total['goods_amount'] = get_price($total['goods_amount']-$discount);
        $total['goods_amount_format'] = price_format($total['goods_amount'], false);
        $total['total_vip_price'] = get_price($total['total_vip_price']-$discount);
        $total['total_vip_price_format'] = price_format($total['total_vip_price'], false);
    	$total['saving'] = get_price($total['market_price'] - $total['goods_amount']);
        $total['saving_format'] = price_format($total['saving'], false);
        $total['save_rate'] = $total['market_price']>0 ? round(($total['market_price'] - $total['goods_amount']) *
                100 / $total['market_price']) . '%' : 0;
        $total['vip_saving'] = get_price($total['market_price'] - $total['total_vip_price']);
        $total['vip_saving_format'] = price_format($total['vip_saving'], false);
        $total['vip_save_rate'] = $total['market_price']>0 ? round(($total['market_price'] - $total['vip_saving']) *
                100 / $total['market_price']) . '%' : 0;
        $total['derivative_price'] = get_price($total['goods_amount']-$total['total_vip_price']);
        $total['derivative_price_format'] = price_format($total['derivative_price'], false);

    	return $total;
    }

    /**
     * 获取其中对应的act_id活动的信息
     * @param $act_id
     * @param $favourable_list
     * @return bool
     */
    public function get_activityinfo($act_id,$favourable_list){
    	foreach ($favourable_list as $activity){
    		if($act_id!=$activity['act_id']){
    			continue;
    		}else{
    			return $activity;
    		}
    	}
    	return false;
    }

    /**
     * 获取购物车中活动信息以及活动相关商品
     * @param $favourable_goods
     * @param bool $flag   是否根据实际情况实时修改数据，例如：不满足换购或赠送条件时，删除相关的换购商品或赠品
     * @return array
     */
    public function get_activity_group_info($favourable_goods,$flag=false){
    	$result = array();
    	foreach ($favourable_goods as $key=>$val){
    		$favourable_info = $val;
    		$goods_total_price = 0;
            $goods_total_vip_price = 0;
            $favourable_goods_total_price = 0;
            $favourable_goods_total_vip_price = 0;
    		$discount = 0;
    		$need_add_price = 0;
    		$can_redemption = 0;
    		foreach ($favourable_info['goods_list'] as $fkey=>$goods){
                $goods['vip_price']=sprintf("%.2f",$goods['vip_price']);
                if($goods['is_check']==1){
                    //统计所有选取的商品的总金额
                    $goods_total_price+=$goods['goods_price']*$goods['goods_number'];
                    $goods_total_vip_price+=$goods['vip_price']*$goods['goods_number'];
                    //统计所有选取的参与活动的商品总金额
                    if(!in_array($goods['giving'],array(1,2))){
                        $favourable_goods_total_price += $goods['goods_price']*$goods['goods_number'];
                        $favourable_goods_total_vip_price += $goods['vip_price']*$goods['goods_number'];
                    }
                }
            }
    		switch ($favourable_info['info'][ 'act_type']){
    			case FAT_GOODS:
    				if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
    					$can_redemption=1;
    				}else{
    					$need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
    				}
    			break;
    			case FAT_PRICE:
    				if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
    					$discount = $favourable_info['info']['act_type_ext'];
    				}else{
    					$need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
    				}
    			break;
    			case FAT_DISCOUNT:
    				if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourable_info['info']['min_amount']>=0){
    					$discount = $goods_total_price * (1 - $favourable_info['info']['act_type_ext'] / 100);
    				}else{
    					$need_add_price = $favourable_info['info']['min_amount']-$favourable_goods_total_price;
    				}
    			break;
                case FAT_DISCOUNT_LIMIT:

                    break;
    		}
            $favourable_info['info']['discount_info'] = $favourable_info['info']['discount'];
            $favourable_info['info']['discount'] = $discount;
            $favourable_info['discount'] = $discount;
    		$favourable_info['goods_total_price'] = $goods_total_price;
            $favourable_info['goods_total_vip_price'] = $goods_total_vip_price;
    		$favourable_info['need_add_price'] = $need_add_price;
    		$favourable_info['can_redemption'] = $can_redemption;
    		$favourable_info['total_amount'] = sprintf("%.2f",$goods_total_price-$discount);
            $favourable_info['total_vip_amount'] = sprintf("%.2f",$goods_total_vip_price-$discount);

            //如果不满足条件，则删除换购商品跟赠品
            if($flag && $can_redemption==0 && $need_add_price>0){
                $favourable_info['goods_list'] = $this->delete_cart_favourable_goods($favourable_info['info']['act_id'],$favourable_info['goods_list']);
                $favourable_info['goods_total_price'] = $favourable_goods_total_price;
                $favourable_info['goods_total_vip_price'] = $favourable_goods_total_vip_price;
                $favourable_info['total_amount'] = $favourable_goods_total_price-$discount;
                $favourable_info['total_vip_amount'] = $favourable_goods_total_vip_price-$discount;
            }

    		$result[] = $favourable_info;
    	}
    	return $result;
    }


    /**
     * 删除购物车中的换购与赠品商品
     * @param $act_id
     * @param $goods_list
     * @return mixed
     */
    public function delete_cart_favourable_goods($act_id,$goods_list){
        $map = array();
        $map['act_id'] = $act_id;
        $map['giving'] = array(in,array(1,2));
        $res = M('cart')->where($map)->delete();
        if($res!==false){
            foreach($goods_list as $key=>$goods){
                if(in_array($goods['giving'],array(1,2))){
                    unset($goods_list[$key]);
                }
            }
        }
        return $goods_list;
    }
    /**
     * 区分赠送与换购类型，返回对应的标签
     * @param int $act_type
     * @param array $favourable_info_gift
     * @return int $activity_tag
     */
    public function check_activity_tag($act_type,$favourable_info_gift,$act_range,$act_range_ext,$min_amount){
        $is_gift = 0;
        $activity_tag = $act_type;
        //如果兑换商品中有商品价格大于0，则为换购标记
        foreach($favourable_info_gift as $g_key=>$gift){
            if($gift['price']>0){
                $is_gift = 1;
                break;
            }
        }
        if($is_gift==1){
            $activity_tag = 5;
        }
        
        if($act_range==3 && is_numeric($act_range_ext) && count($favourable_info_gift)==1 && $act_info['act_type']==0 && $min_amount==0 && $goods_list[$favourable_info_gift[0]['id']]==0){
            $activity_tag = 7;
        }
        
        return $activity_tag;
    }

    /**
     * 处理购物车中商品的活动信息
     * @param array $cart_goods
     * @param array $favourable_list
     * @return array $cart_goods
     */
    public function convert_cart_goods($cart_goods,$favourable_list,$change_data=false){
    	$wid = I('post.wid', 8, 'int');

    	foreach ($cart_goods as $key=>$val){
    		$goods_id = $val['goods_id'];
    		$goods_cate = $val['cat_id'];
    		$goods_brand= $val['brand_id'];
            //商品可参与的活动列表
    		$goods_activity_list = array();

    		$is_on_activity = false;
            foreach ($favourable_list as $f_key => $f_avl) {
                //如果当前商品是赠品或者换购商品，只参与一个活动
                if(in_array($cart_goods[$key]['giving'],array(1,2)) && $cart_goods[$key]['act_id'] == $f_avl['act_id']){
                    //商品可参与的活动
                    $goods_activity = array();
                    $goods_activity['act_id'] = $f_avl['act_id'];
                    $goods_activity['act_name'] = $f_avl['act_name'];
                    $goods_activity['act_tag'] = $f_avl['act_tag'];
                    $goods_activity['current_act'] = 1;
                    $is_on_activity = true;
                    $goods_activity_list[] = $goods_activity;
                }elseif($cart_goods[$key]['giving']==0){    //普通商品，获取商品的活动信息
                    $act_range_ext = explode(',', $f_avl['act_range_ext']);
                    //如果优惠范围为分类且设置包含子分类，则获取当前设置分类的所有子分类
                    if($f_avl['act_range'] == 1 && $f_avl['is_include_subcategory'] == 1){
                        $act_range_ext = $this->get_sub_cate($act_range_ext);
                    }
                    if ($f_avl['act_range'] == 0 || ($f_avl['act_range'] == 1 && in_array($goods_cate, $act_range_ext)) || ($f_avl['act_range'] == 2 && in_array($goods_brand, $act_range_ext)) || ($f_avl['act_range'] == 3 && in_array($goods_id, $act_range_ext))) {
                        if ($cart_goods[$key]['act_id'] == 0 && $change_data) {
                            $savedata = array();
                            $savedata['act_id'] = $f_avl['act_id'];
                            $this->change_cart_goods_act($cart_goods[$key]['rec_id'], $savedata);
                            $cart_goods[$key]['act_id'] = $f_avl['act_id'];
                        }

                        //商品可参与的活动
                        $goods_activity = array();
                        $goods_activity['act_id'] = $f_avl['act_id'];
                        $goods_activity['act_name'] = $f_avl['act_name'];
                        $goods_activity['act_tag'] = $f_avl['act_tag'];
                        if ($cart_goods[$key]['act_id'] == $f_avl['act_id']) {
                            $goods_activity['current_act'] = 1;
                            $is_on_activity = true;
                        } else {
                            $goods_activity['current_act'] = 0;
                        }
                        $goods_activity_list[] = $goods_activity;
                    }
                }
            }

            //商品可参与的活动列表
    		$cart_goods[$key]['activity_list'] = $goods_activity_list;
            //判断商品是否同时参与多个活动
    		if(count($goods_activity_list)>1){
    			$cart_goods[$key]['muti_acivity'] = 1;
    		}else{
    			$cart_goods[$key]['muti_acivity'] = 0;
    		}
    		if(!$is_on_activity && $change_data){
    			//修改当前商品的所属活动
                //如果商品当前的活动已经结束，则恢复为普通的商品状态或修改为参与其他活动
    			//如果是赠品或换购商品，则从购物车中删除
                if($cart_goods[$key]['giving']==1 || $cart_goods[$key]['giving']==2){
                    $this->remove_cart_goods($cart_goods[$key]['rec_id']);
                    unset($cart_goods[$key]);
                }else{
                    $data = array();
                    if(count($goods_activity_list)>0 && $cart_goods[$key]['is_quota']==0 && count($goods_activity_list)>0){
                        $act_temp = current($goods_activity_list);
                        $data['act_id'] = $act_temp['act_id'];
                        if(count($act_temp['gift']>0)){
                            $data['is_gift'] = $act_temp['act_id'];
                        }
                    }elseif(count($goods_activity_list)<=0 && $cart_goods[$key]['is_quota']==0){
                        $data['act_id'] = 0;
                        $data['is_gift'] = 0;
                    }
                    $this->change_cart_goods_act($cart_goods[$key]['rec_id'], $data);
                    $cart_goods[$key]['act_id'] =$data['act_id'];
                    $cart_goods[$key]['is_gift'] = $data['is_gift'];
                }
    		}

			if ($cart_goods[$key]['is_buynow'] == 0){
//    			促销价商品处理
				$cart_goods[$key] = $this->check_promote_price_by_time($cart_goods[$key]);
				if (empty($cart_goods[$key]['promote_price'])) {
					$cart_goods[$key]['promote_end_date'] = '';
					$cart_goods[$key]['promote_start_date'] = '';
					$cart_goods[$key]['promote_price'] = 0;
				}
			}
//			秒杀商品处理
			else if ($cart_goods[$key]['is_buynow'] == 1){
				$buyNowGoodsService = new BuyNowGoodsService($cart_goods[$key]['user_id'], $wid);
				$cart_goods[$key] = $buyNowGoodsService->handleBuyNowGoodsDataByCart($cart_goods[$key]);
				$cart_goods[$key]['promote_end_date'] = '';
				$cart_goods[$key]['promote_start_date'] = '';
				$cart_goods[$key]['promote_price'] = 0;
			}
    	}
//		dd($cart_goods);
    	return $cart_goods;
    }

    /**
     * 获取对应分类的所有子分类
     * @param $cates
     * @return array
     */
    public function get_sub_cate($cates){
        if(!empty($cates)){
            $cid_array=array();
            if(is_array($cates)){
                foreach($cates as $cat_id){
                    //获取当前分类的所有子分类
                    $cat_list = D('category')->cat_list($cat_id,0,false,0,false);
                    foreach ($cat_list as $cate_val){
                        $cid_array[] = $cate_val['cat_id'];
                    }
                    array_push($cid_array,$cat_id);
                }
            }else{
                //获取当前分类的所有子分类
                $cat_list = D('category')->cat_list($cates,0,false,0,false);
                foreach ($cat_list as $cate_val){
                    $cid_array[] = $cate_val['cat_id'];
                }
                array_push($cid_array,$cates);
            }

            $cid_array = array_unique($cid_array);
            return $cid_array;
        }else{
            return $cates;
        }

    }
    /**
     * 检查当前购物车商品当前的活动是否存在或者过期
     * @param $cart_goods
     * @param $favourbale_list
     * @return bool
     */
    public function is_exit_activity($cart_goods,$favourbale_list){
        $flag = true;
        $current_activity_list = array();
        foreach ($favourbale_list as $activity){
            $current_activity_list[] = $activity['act_id'];
        }

        foreach($cart_goods as $goods){
            if($goods['act_id']>0 && !in_array($goods['act_id'],$current_activity_list)){
                $flag = false;
                break;
            }
        }

        return $flag;
    }

    public function check_activity_status($act_id){
        $can_redemption=0;
        $need_add_price= 0;
        $favourbale_info = M('avourable_activity')->where(array('act_id'=>$act_id))->find();

        $map = array();
        $map['act_id'] = $act_id;
        $map['giving'] = array('not in',array(1,2));
        $field = "sum(goods_price*goods_number) as favourable_price";
        $cart_info = M('cart')->field($field)->where($map)->find();
        $favourable_goods_total_price = $cart_info['favourable_price'];

        if($favourable_goods_total_price>0 && $favourable_goods_total_price-$favourbale_info['min_amount']>=0){
            $can_redemption=1;
        }else{
            $need_add_price = $favourbale_info['min_amount']-$favourable_goods_total_price;
        }

        $result['act_id'] = $favourbale_info['act_id'];
        $result['can_redemption'] = $can_redemption;
        $result['need_add_price'] = $need_add_price;

        return $result;
    }
    /**
     * 修改购物车商品活动数据
     * @param int $rec_id
     * @param array $data
     */
    public function change_cart_goods_act($rec_id,$data){
    	$res = M('cart')->where(array('rec_id'=>$rec_id))->save($data);
    	return $res;
    }


    /**
     * 删除购物车中的商品
     * @param unknown $rec_id
     */
    public function remove_cart_goods($rec_id){
    	M('cart')->where(array('rec_id'=>$rec_id))->delete();
    }

    public function favourable_list_flow($uid,$wid){
        if(empty($wid)){
            $wid = C('DEFAULT_WID');
        }
    	//获取当前用户等级
    	$user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        if(empty($user_rank)){
            $user_rank = 1;
        }
    	$now = gmtime();

    	$map = array();

    	$map["start_time"] = array('elt',$now);
    	$map["end_time"] = array('egt',$now);
    	$map['act_type'] = array('in',array(FAT_GOODS, FAT_PRICE, FAT_DISCOUNT, FAT_DISCOUNT_LIMIT));
    	$map['_string'] = "FIND_IN_SET(".$user_rank.", user_rank)";

    	//获取当前用户可参与的活动（除抢购外）
    	$favourable_activity_list = M('favourable_activity')->where($map)->order('sort_order desc,act_id desc')->select();
    	foreach ($favourable_activity_list as $key=>$favourable) {

    		$favourable ['start_time'] = local_date(C('time_format'), $favourable ['start_time']);
    		$favourable ['end_time'] = local_date(C('time_format'), $favourable ['end_time']);
    		$favourable ['formated_min_amount'] = price_format($favourable ['min_amount'], false);
    		$favourable ['formated_max_amount'] = price_format($favourable ['max_amount'], false);
    		$favourable_gift = unserialize($favourable ['gift']);

            $gift_list = array();
            //获取赠品或换购商品图
            foreach($favourable_gift as $key_gift=>$gift){
                $goods = M('goods_wid_'.$wid)->field('goods_img,practical_num as goods_stock,is_on_sale,is_delete')->where(array('goods_id'=>$gift['id']))->find();
                if($goods['is_on_sale']==1 && $goods['is_delete']==0){
                    $favourable_gift[$key_gift]['goods_img'] = img_init($goods['goods_img']);
                    $favourable_gift[$key_gift]['goods_stock'] = $goods['goods_stock'];
                    $gift_list[] = $favourable_gift[$key_gift];
                }
            }

            $favourable ['gift'] = $gift_list;
    		$favourable ['quota'] = unserialize($favourable ['quota']);
            $favourable ['act_tag'] = $this->check_activity_tag($favourable ['act_type'],$favourable ['gift'],$favourable ['act_range'],$favourable ['act_range_ext'],$favourable ['min_amount']);
            $favourable['discount'] = json_decode($favourable['discount'], true);
    		$favourable_list [] = $favourable;
    	}
    	return $favourable_list;

    }
    /**
     * 操作购物车商品
     * @param int $uid 用户ID
     * @param int $goods_id  商品ID
     * @param int $num 商品数量
     * @param string $spec 商品属性
     * @param int $wid 仓库ID
     * @param string $operate 操作类型
     */

    function __construct() {

    }

    public function change_cart_num($uid, $goods_id, $num,$spec='',$wid=0,$operate='add',$act_id=0,$act_type,$reset_giving){
        if(!isset($goods_id) || empty($goods_id)){
            return array("status"=>0,"msg"=>"商品ID错误");
        }

        if(empty($num)){
            $num=1;
        }

        //检验商品属性
        if($spec){
            $spec=explode(',', $spec);
        }
        $is_spec_true=$this->check_spec($goods_id,$spec);
        if(!$is_spec_true['status']){
            return $is_spec_true;
        }

        // 更新：如果是一步购物，先清空购物车    
        if (C('one_step_buy') == '1') {
            D('NewCart')->clear_cart($uid);
        }

        $cart_goods = $this->is_exists_record( $uid, $goods_id ,$act_id,$act_type);



        if($cart_goods){
            //当前购物车商品数量
            $current_num = $cart_goods['goods_number'];
        }else{
            $current_num =0;
        }
            //获取商品起购数量
            $min_buy_num = $this->min_buy_num($goods_id);


        //不是限购商口加减删处理
            if($operate == "add"){
                $do_num = $current_num+$num;

                if($do_num<$min_buy_num){
                    $do_num = $min_buy_num;
                }
            }elseif($operate == "dec"){
                $do_num = $current_num-$num;
                if($do_num<$min_buy_num){
                    $do_num = 0;
                }
            }elseif ($operate == 'del'){
                $do_num = 0;
            }



       // 更新：添加到购物车
        $re_msg=$this->change_cart($uid,$goods_id, $do_num, $spec, $wid,$act_id,$act_type,$operate);
        if (!$re_msg['status']) {
            return $re_msg;
        }

        return array('status'=>1);
    }


    /*
     * 增减购物车
     * */

    public function change_cart($uid,$goods_id,$num=1,$spec = array(),$wid=0,$act_id=0,$act_type,$operate,$_parent_id=0){

        $Model=new Model();
        //获取会员等级
        $user_rank = D('users')->where(array('user_id'=>$uid))->getField('user_rank');
        $user_rank_temp=$user_rank;

        /* 取得商品信息 */
        if(empty($_SESSION['discount']) || $_SESSION['discount']=='0.00'){
            $user_rank = D('Users')->get_user_rank($uid);
            $_SESSION['discount']=$user_rank['discount'];
        }

        //获取商品会员价格
        $goods=$this->get_rank_goods_info($goods_id, $user_rank);
        if (empty($goods)) {
            return array('status'=>0,'msg'=>'商品不存在或已下架');
        }

        if($act_id==0){
            $act_id=$this->get_goods_activity($user_rank_temp, $goods);
        }

        /* 是否正在销售 */
        if ($goods['is_on_sale'] == 0 && $operate=='add') {
            return array('status'=>0,'msg'=>'商品已下架');
        }

        /* 不是配件时检查是否允许单独销售 */
        if (empty($parent) && $goods['is_alone_sale'] == 0) {
            return array('status'=>0,'msg'=>'该商品不能单独销售');
        }


        /* 如果商品有规格则取规格商品信息 配件除外 */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "products WHERE goods_id = '$goods_id' LIMIT 0, 1";
        $prod = $Model->query($sql);
        if (D('Goods')->is_spec($spec) && !empty($prod)) {
            $product_info = D('Goods')->get_products_info($goods_id, $spec);
        }

        if (empty($product_info)) {
            $product_info = array('product_number' => '', 'product_id' => 0);
        }


        // 检查：库存：系统启用了库存，检查输入的商品数量是否有效
        if (C('use_storage') == 1 && $operate=='add') {
            $is_valid_true=$this->check_num_valid($goods_id,$wid,$num);
            if(!$is_valid_true['status']){
                return $is_valid_true;
            }
        }


        /* 计算商品的促销价格 */
        $spec_price = D('Goods')->spec_price($spec);
        $goods_price = D('Goods')->get_final_price($goods_id, $num, true, $spec, $uid);

        $goods['market_price'] += $spec_price;
        $goods_attr = D('Goods')->get_goods_attr_info($spec);
        $goods_attr_id = join(',', $spec);

        /* 初始化要插入购物车的基本件数据 */
        $parent = array(
			'user_id' => $uid,
			'session_id' => SESS_ID,
			'goods_id' => $goods_id,
			'goods_sn' => addslashes($goods['goods_sn']),
			'product_id' => $product_info['product_id'],
			'goods_name' => addslashes($goods['goods_name']),
			'market_price' => $goods['market_price'],
			'goods_attr' => addslashes($goods_attr),
			//'goods_attr_id' => $goods_attr_id,
			'is_real' => $goods['is_real'],
			'extension_code' => $goods['extension_code'],
			'is_gift' => 0,
			'is_quota' => 0,
			'is_shipping' => $goods['is_shipping'],
			'is_presell' => $goods['is_presell'],
			'rec_type' => CART_GENERAL_GOODS,

        );
        if(!empty($goods_attr_id)){
            $parent['goods_attr_id']=$goods_attr_id;
        }

        //分类限购检查
        $res = D('Goods')->check_cat_max_buy_number($parent,$goods_price,$uid,$num);

        /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
        /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
        /* 受此优惠 */
        $basic_list = array();
        $sql = "SELECT parent_id, goods_id, goods_price " ."FROM " . C('DB_PREFIX') ."group_goods WHERE goods_id = '$goods_id'" ." AND goods_price < '$goods_price'" ." AND parent_id = '$_parent_id'" ." ORDER BY goods_price";
        $res = $Model->query($sql);
        foreach ($res as $key=>$row) {
            $basic_list[$row['parent_id']] = $row['goods_price'];
        }
        /* 取得购物车中该商品每个基本件的数量 */
        $basic_count_list = array();

        if ($basic_list) {
            $sql = "SELECT goods_id, SUM(goods_number) AS count " .
                "FROM " . C('DB_PREFIX') .
                "cart WHERE user_id = '" . $uid . "'" .
                " AND parent_id = 0" .
                " AND extension_code <> 'package_buy' " .
                " AND goods_id " . db_create_in(array_keys($basic_list)) .
                " GROUP BY goods_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['goods_id']] = $row['count'];
            }
        }

        /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
        /* 一个基本件对应一个该商品配件 */
        if ($basic_count_list) {
            $sql = "SELECT parent_id, SUM(goods_number) AS count " .
                "FROM " .C('DB_PREFIX') .
                "cart WHERE user_id = '" . $uid . "'" .
                " AND goods_id = '$goods_id'" .
                " AND extension_code <> 'package_buy' " .
                " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
                " GROUP BY parent_id";
            $res = $Model->query($sql);
            foreach ($res as $key=>$row) {
                $basic_count_list[$row['parent_id']] -= $row['count'];
            }
        }

        /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
        foreach ($basic_list as $parent_id => $fitting_price) {
            /* 如果已全部插入，退出 */
            if ($num <= 0) {
                break;
            }

            /* 如果该基本件不再购物车中，执行下一个 */
            if (!isset($basic_count_list[$parent_id])) {
                continue;
            }

            /* 如果该基本件的配件数量已满，执行下一个基本件 */
            if ($basic_count_list[$parent_id] <= 0) {
                continue;
            }

            /* 作为该基本件的配件插入 */
            $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
            $parent['goods_number'] = min($num, $basic_count_list[$parent_id]);
            $parent['parent_id'] = $parent_id;

            /* 添加 */
            M('cart')->add($parent);
            /* 改变数量 */
            $num -= $parent['goods_number'];
        }



        /* 检查该商品是否已经存在在购物车中 */
        $row = $this->get_goods_info($uid, $goods_id, $spec,$act_type);

        /* 如果数量不为0，作为基本件插入 */
        if ($num > 0) {

            if ($row) { //如果购物车已经有此物品，则更新
                $cartdata=array();
                if($row['act_id'] && in_array($row['giving'],array('0'))){
                    //添加活动普通商品
                    //$re_act=$this->check_activity_valid($user_rank_temp, $act_id, $goods,$act_type);
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $row['act_id'],$goods_id);
                    $act_goods_amount+=$goods_price*$num;
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }



                    if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$gift[0]['id']]==0 && $row['is_check']=='1'){

                        //买一赠一
                        if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            $change_num=$act_info['act_type_ext'];
                        }else{
                            $change_num=$num;
                        }
                        $change_num1=$change_num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$change_num*2;
                        }

                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){

                            $re_msg=$this->change_cart($uid,$gift[0]['id'],$change_num,array(),$wid,$row['act_id'],'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }else if(count($gift)==1 && $act_info['act_type']==0 && $goods_list[$gift[0]['id']]==0 && $row['is_check']=='1'){
                        $change_num1=$num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$num+1;
                        }
                        
                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],1,array(),$wid,$row['act_id'],'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }else if(floatval($act_info['min_amount'])>floatval($act_goods_amount)){
                        //不满足优惠条件，则清除换购和赠品
                        $this->clean_act_giving_goods($uid,$act_info['act_id']);
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$goods_price
                    );
                }else if($row['act_id'] && in_array($row['giving'],array('3'))){
                    //限购活动商品
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    if(!$act_info || $act_info['act_type']<>3 || !($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext'])))){
                        return array('status'=>0,'msg'=>'该商品不符合限购活动或已过期');
                        $this->clean_act_quota_goods($uid,$act_info['act_id']);
                    }
                    $quota=unserialize($act_info['quota']);
                    $quota_i=array();
                    if($act_info['act_range']==1){
                        foreach($quota as $item){
                            if($item['id']==$goods['cat_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }else if($act_info['act_range']==2){
                        foreach($quota as $item){
                            if($item['id']==$goods['brand_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }

                    }else if($act_info['act_range']==3){
                        foreach($quota as $item){
                            if($item['id']==$goods['goods_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }

                    /* 检查是否已参与过该活动 */
        			$quota_favourable = $this->activity_favourable_quota($row['act_id'],'',$uid);
        			if ($quota_favourable && $quota_favourable['num'] > 0) {
        				return array('status'=>0,'msg'=>"此活动您已参与过");
        			}

                    if($quota_i['count']>0 && $quota_i['count']<$num){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    //活动数量限制
                    $this_act_num=$this->get_quota_goods_num($uid, $act_id,$goods_id);

                    if($act_info['act_type_ext']>0 && $act_info['act_type_ext']<($this_act_num+$num)){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$quota_i['price']
                    );

                }else if($row['act_id'] && in_array($row['giving'],array('2','1'))){
                    //添加活动换购商品或赠品
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $row['act_id'],$goods_id);
                    $act_info=$this->get_act_info($row['act_id'],$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    $giving_num=$this->get_giving_goods_num($uid, $row['act_id'],$goods_id);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }
                    if(!in_array($goods_id,$goods_id_list)){
                        return array('status'=>0,'msg'=>'该商品不符合该活动或已过期');
                    }




                    if(!($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$goods_id]==0)){
                        if(floatval($act_goods_amount)<floatval($act_info['min_amount'])){
                            $this->clean_act_giving_goods($uid,$act_info['act_id']);
                            //return array('status'=>0,'msg'=>'不满足该活动条件');
                        }
                        if($giving_num+$num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            //换购或赠品最大数量不能超过设置数
                            return array('status'=>0,'msg'=>'换购或赠品超过最大数量');
                        }
                    }

                    $cartdata=array(
                        'goods_number'=>$num,
                        'goods_price'=>$goods_list[$goods_id]
                    );

                }
				else if(in_array($row['giving'],array('4'))) {
                	if ($num < $row['goods_number']) {
						$cartdata = array(
							'goods_number' => $num,
							'goods_price' => $goods_price
						);
					}
					else
					{
//                	促销价范围
						$promoteService = new PromoteService();
						$goodsNumber = $num;
						$is_promote = $promoteService->isPromote($uid, $goods_id, $goodsNumber);
						if ($is_promote === true) {
							$cartdata = array(
//								'act_id' => $act_id,
								'goods_number' => $num,
								'goods_price' => $goods_price
							);
						}else{
							return array(
								'status'	=>	0,
								'msg'		=>	$promoteService->getErrorMessage(),
							);
						}
					}
				}

//				秒杀价处理
				else if(in_array($row['giving'],array('5'))) {

                	if ($operate == 'dec') {
						$cartdata = array(
							'goods_number' => $row['goods_number'] - $num,
							'goods_price' => $goods_price
						);
					}
					else if ($operate == 'add'){
						$buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
						$goodsNumber = $num;
						$is_buy_now = $buyNowGoodsService->isBuyNowGoods($goods_id, $goodsNumber);
						if ($is_buy_now === true) {
							$cartdata = array(
								'act_id' => $act_id,
								'goods_number' => $goodsNumber,
								'goods_price' => $goods_price
							);
						}else{
							return array(
								'status'	=>	0,
								'msg'		=>	$buyNowGoodsService->getErrorMessage(),
							);
						}
					}

				}
//				普通商品
				else {
                    $act_id=$this->get_goods_activity($user_rank_temp, $goods);
                    $cartdata = array(
                        'act_id' => $act_id,
                        'goods_number' => $num,
                        'goods_price' => $goods_price
                    );
                }

                $rec_id = $row['rec_id'];

                $where = array('rec_id'=>$rec_id,'user_id'=>$uid,'goods_id'=>$goods_id);
                M('Cart')->where($where)->save($cartdata);


            } else { //购物车没有此物品，则插入
                if($act_id && empty($act_type)){
                    $act_info = $this->get_act_info($act_id,$user_rank_temp);
                    if($act_info['act_type']=='3'){
                        //$act_type='is_quota';
                    }
                }

                $parent['goods_price'] = max($goods_price, 0);
                $parent['goods_number'] = $num;
                $parent['parent_id'] = 0;

                if($act_id && $act_type=='is_exchange'){

                    //添加活动换购商品或赠品
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    $giving_num=$this->get_giving_goods_num($uid, $act_id,$goods_id);

                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }
                    if(!in_array($goods_id, $goods_id_list) || $act_info['act_type']!='0'){
                        return array('status'=>0,'msg'=>'该商品不符合该活动或已过期');
                    }

                    //换购或赠品最大数量不能超过设置数
                    if($giving_num+$num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                        $num=$act_info['act_type_ext'];
                    }

                    if(!($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['min_amount']==0) && floatval($act_goods_amount)<floatval($act_info['min_amount'])){
                        //return array('status'=>0,'msg'=>'不满足该活动条件');                 
                    }

                    $goods_price=$goods_list[$goods_id];
                    if(floatval($goods_price)){
                        $parent['giving'] = 2;
                    }else{
                        $parent['giving'] = 1;
                    }
                    $parent['goods_price'] = $goods_price;
                    $parent['act_id'] = $act_info['act_id'];
                    $parent['is_gift'] = $act_id;

                }else if($act_id && $act_type=='is_quota'){

                    //添加限购活动商品
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);

                    if(!$act_info || $act_info['act_type']<>3 || !($act_info['act_range']==0 || $act_info['act_range']==1 && in_array($goods['cat_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==2 && in_array($goods['brand_id'],explode(",",$act_info['act_range_ext'])) || $act_info['act_range']==3 && in_array($goods['goods_id'],explode(",",$act_info['act_range_ext'])))){
                        return array('status'=>0,'msg'=>'该商品不符合限购活动或已过期');
                    }
                    $quota=unserialize($act_info['quota']);
                    $quota_i=array();
                    if($act_info['act_range']==1){
                        foreach($quota as $item){
                            if($item['id']==$goods['cat_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }else if($act_info['act_range']==2){
                        foreach($quota as $item){
                            if($item['id']==$goods['brand_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }

                    }else if($act_info['act_range']==3){
                        foreach($quota as $item){
                            if($item['id']==$goods['goods_id']){
                                $quota_i['count']=$item['count'];
                                $quota_i['price']=$item['price'];
                                break;
                            }
                        }
                    }

                    /* 检查是否已参与过该活动 */
                    $quota_favourable = $this->activity_favourable_quota($act_id,'',$uid);
                    if ($quota_favourable && $quota_favourable['num'] > 0) {
                        return array('status'=>0,'msg'=>"此活动您已参与过");
                    }

                    if($quota_i['count']>0 && $quota_i['count']<$num){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    //活动数量限制
                    $this_act_num=$this->get_quota_goods_num($uid, $act_id,$goods_id);

                    if($act_info['act_type_ext']>0 && $act_info['act_type_ext']<($this_act_num+$num)){
                        return array('status'=>0,'msg'=>"此活动限购" . $quota_i['count'] . "份，超出限购数量!");
                    }

                    $parent['giving'] = 3;
                    $parent['act_id'] = $act_id;
                    $parent['goods_price'] = $quota_i['price'];
                    $parent['is_quota'] = $act_id;

                }
                else if ($act_type=='is_promote'){
					//					促销价范围处理
					$promoteService = new PromoteService();
					$is_promote = $promoteService->isPromote($uid, $goods['goods_id'], $num);
					if ($is_promote === true) {
						$parent['giving'] = 4;
					}else{
						return array(
							'status'	=>	0,
							'msg'		=>	$promoteService->getErrorMessage(),
						);
					}
				}
//				秒杀商品处理
				else if ($act_type=='is_buynow'){
					$buyNowGoodsService = new BuyNowGoodsService($uid, $wid);
					$is_buy_now = $buyNowGoodsService->isBuyNowGoods($goods['goods_id'], $num);

					if ($is_buy_now === true) {
						$parent['giving'] = 5;
					}
					else{
						return array(
							'status'	=>	0,
							'msg'		=>	$buyNowGoodsService->getErrorMessage(),
						);
					}
				}
				else{

                    //                    第二件半价
//                    $favourableModel = D('FavourableActivity');
//                    $discount = $favourableModel->get_is_discount($uid, $goods['goods_id']);
////                    判断是否当前商品已参与活动,防止冲突
//                    if (empty($act_id)) {
//                        $act_id = $discount['act_id'];
//                    }
                    $parent['act_id'] = $act_id;
                }

                $rec_id = M('Cart')->add($parent);

                if($act_id && $act_type!='is_exchange'){
                    //添加活动普通商品
                    //$re_act=$this->check_activity_valid($user_rank_temp, $act_id, $goods,$act_type);
                    $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);
                    $act_goods_amount+=$goods_price*$num;
                    $act_info=$this->get_act_info($act_id,$user_rank_temp);
                    $gift=unserialize($act_info['gift']);
                    foreach($gift as $item){
                        $goods_id_list[]=$item['id'];
                        $goods_price_list[]=$item['price'];
                        $goods_list[$item['id']]=$item['price'];
                    }

                    if($act_info['act_range']==3 && is_numeric($act_info['act_range_ext']) && count($gift)==1 && $act_info['act_type']==0 && $act_info['min_amount']==0 && $goods_list[$gift[0]['id']]==0){
                        //买一赠一
                        if($num>$act_info['act_type_ext'] && floatval($act_info['act_type_ext'])!=0){
                            $change_num=$act_info['act_type_ext'];
                        }else{
                            $change_num=$num;
                        }
                        $change_num1=$change_num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$change_num*2;
                        }

                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],$change_num,'',$wid,$act_id,'is_exchange');
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }


                    }else if(count($gift)==1 && $goods_list[$goods_id]==0 && $act_info['act_type']==0 && floatval($act_info['min_amount'])<floatval($act_goods_amount) && $goods_list[$gift[0]['id']]==0){
                        $change_num1=$num;
                        if($gift[0]['id']==$goods_id){
                            $change_num1=$num+1;
                        }
                        //单一赠品，符合条件自动添加赠品
                        $is_valid_true=$this->check_num_valid($gift[0]['id'],$wid,$change_num1);
                        if($is_valid_true['status']){
                            $re_msg=$this->change_cart($uid,$gift[0]['id'],1,array(),$wid,$act_id,'is_exchange',0);
                            if(!$re_msg['status']){
                                return $re_msg;
                            }
                        }
                    }

                }

            }
        }else{
            $act_goods_amount=$this->get_act_cart_goods_total($uid, $act_id,$goods_id);

            $act_info=$this->get_act_info($act_id,$user_rank_temp);
            if(floatval($act_info['min_amount'])>floatval($act_goods_amount) || floatval($act_goods_amount)==0){
                //不满足优惠条件，则清除换购和赠品
                $this->clean_act_giving_goods($uid,$act_info['act_id']);
            }

            $this->remove_shopping_cart_goods($uid, $row['rec_id']);
        }

        return array('status'=>1,'goods_price'=>$goods_price);
    }

    /**
     * 插入活动id
     * Created by Jerry
     * @param $cart_id
     * @param $act_id
     * @return bool
     */
    protected function update_cart_for_act_id($cart_id, $act_id)
    {
        $where = array(
            'rec_id'    =>  $cart_id,
        );

        $rs = $this->where($where)->setField('act_id', $act_id);
        return $rs;
    }
    
    /**
     * 限购活动中的参与信息
     */
    public function activity_favourable_quota($act_id, $goods_id = null,$uid) {
        $sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id'" . " GROUP BY act_id";
        if ($goods_id) {
            $sql = "SELECT act_id, COUNT(*) AS num " . "FROM " . C('DB_PREFIX') . "activity_quota  WHERE user_id = " . $uid . " AND act_id='$act_id' AND goods_id=" . $goods_id . " GROUP BY act_id";
        }
        $model = new  Model();
        $res =$model->query($sql);
        return current($res);
    }

    /**
     * 购物车中的限购产品
     */
    public function cart_favourable_quota($act_id, $goods_id = null,$uid='') {
        $map = array();
        $map['rec_type'] = CART_GENERAL_GOODS;
        $map['is_quota'] = $act_id;
        if($goods_id){
            $map['goods_id'] = $goods_id;
        }

        $map['user_id']  = $uid;
        $res = $this->field("is_quota, SUM(goods_number) AS num")->where($map)->group('is_quota')->find();
        return $res;
    }

    public function check_act_giving_vaild_exits($uid,$goods_id){
        //
    }

    public function clean_act_quota_goods($uid,$act_id){
        M("cart")->where(array('user_id'=>$uid,'act_id'=>$act_id,giving=>array('in','3')))->delete();
    }

    public function clean_act_giving_goods($uid,$act_id){
        M("cart")->where(array('user_id'=>$uid,'act_id'=>$act_id,giving=>array('in','1,2')))->delete();
    }

    /**
     * 获取参考活动商品的总价格
     * @param int $uid 用户ID
     * @param int $act_id 活动ID
     */
    public function get_act_cart_goods_total($uid,$act_id,$goods_id=0){
        $Model=new Model();
        $sql = 'SELECT SUM(goods_price * goods_number) AS amount  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving=0 AND rec_type = '".CART_GENERAL_GOODS ."' and  goods_id<>'".$goods_id."' and is_check='1'";
        $row = $Model->query($sql);
        $act_amount=$row[0]['amount'];
        return $act_amount;
    }

    /**
     * 获取优惠活动信息
     * @param int $act_id 活动ID
     * @return array
     */
    public function get_act_info($act_id,$user_rank){
        if(empty($user_rank)){
            $user_rank=1;
        }
        $Model=new Model();
        $sql = 'SELECT start_time,end_time,act_name,act_id,act_range,act_range_ext,act_type,act_type_ext,min_amount,max_amount,gift,quota FROM ' . C('DB_PREFIX') . 'favourable_activity ' ." WHERE start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and act_id = '" . $act_id . "' order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row[0];
        }else{
            return false;
        }
    }

    /**
     * 获取用户活动的换购或赠品数量
     * @param int $act_id 活动ID
     */
    public function get_giving_goods_num($uid,$act_id,$goods_id=0){
        $Model=new Model();
        $sql = 'SELECT count(*) AS act_count  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving in('1','2') and goods_id<>$goods_id";
        $row = $Model->query($sql);
        return $row[0]['act_count'];
    }

    /**
     * 获取该限购商品数量
     * @param int $act_id 活动ID
     */
    public function get_quota_goods_num($uid,$act_id,$goods_id=0){
        $Model=new Model();
        $sql = 'SELECT SUM(goods_number) AS act_number  FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND act_id=$act_id AND giving in('3') and goods_id<>$goods_id";
        $row = $Model->query($sql);
        return $row[0]['act_number'];
    }



    /**
     *
     * @param int $user_rank 会员等级ID
     * @param int $act_id 活动ID
     * @param array $goods 商品信息
     * @param string $act_type 活动类型
     */
    public function check_activity_valid($user_rank,$act_id,$goods,$act_type=''){
        $Model=new Model();
        if($act_type=='is_exchange'){
            $sql="select gift,act_type_ext from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and act_type=0 and act_id=$act_id";
            $result = $Model->query($sql);
            if($result[0]){
                foreach(unserialize($result[0]['gift']) as $item){
                    if($item['id']==$goods['goods_id']){
                        return true;
                    }
                }
                return false;

            }else{
                return false;
            }
        }else{
            $sql="select act_id from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and (act_range=0 or act_range=1 and act_range_ext=".$goods['cat_id']." or act_range=2 and act_range_ext=".$goods['brand_id']." or act_range=3 and act_range_ext=".$goods['goods_id'].") and act_id=$act_id";
            $result = $Model->query($sql);
            if($result[0]){
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * 获取优惠活动信息
     * @param int $act_id 活动ID
     */
    public function get_activity_info($act_id,$goods_id){
        $Model=new Model();
        $sql="select gift,act_type_ext from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and act_type=0 and act_id=$act_id";
        $result = $Model->query($sql);
        if($result[0]){
            $goods_act=array();
            $goods_act['max_num']=$result[0]['act_type_ext'];
            foreach(unserialize($result[0]['gift']) as $item){
                if($item['id']==$goods_id){
                    $goods_act['act_price']=$item['price'];
                    break;
                }
            }
            return $goods_act;

        }else{
            return 0;
        }

    }

    /**
     * 获取符合商品的优惠活动
     * @param $user_rank
     * @param $goods
     * @return int
     */
    public function get_goods_activity($user_rank,$goods){
        $Model=new Model();
        $sql="select act_id from " . C('DB_PREFIX') . "favourable_activity where start_time<=".gmtime()." and end_time>".gmtime()." and FIND_IN_SET($user_rank,user_rank) and (act_range=0 or act_range=1 and act_range_ext=".$goods['cat_id']." or act_range=2 and act_range_ext=".$goods['brand_id']." or act_range=3 and act_range_ext=".$goods['goods_id'].") and act_type in(0,1,2,3) order by sort_order asc limit 1";
        $result = $Model->query($sql);
        if($result[0]){
            return $result[0]['act_id'];
        }

        /**
         * 第二件半价
         */
//        $favourableModel = D('FavourableActivity');
//        $favourableData = $favourableModel->get_is_discount(0, $goods['goods_id'], $user_rank);
//
//        if (!empty($favourableData)) {
//            return $favourableData['act_id'];
//        }

        return 0;
        
    }



    /**
     * 获取商品会员等级价格
     * @param int $goods_id 商品ID
     * @param int $user_rank 会员等级ID
     */
    public function get_rank_goods_info($goods_id,$user_rank){
        if(empty($user_rank)){
            $user_rank['discount']=1;
            $user_rank['user_rank']=1;
        }
        $Model=new Model();
        $sql = "SELECT g.cat_id,g.brand_id,g.goods_id,g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date,g.promote_end_date, g.goods_weight, g.integral, g.extension_code,g.goods_number, g.is_alone_sale, g.is_shipping,g.is_presell, g.promote_goods_number, g.promote_today_number, g.promote_number," ." IFNULL(mp.user_price, g.shop_price * ".$user_rank['discount'].") AS shop_price FROM " . C('DB_PREFIX') . "goods AS g " ." LEFT JOIN " . C('DB_PREFIX') . "member_price AS mp " ."ON mp.goods_id = g.goods_id AND mp.user_rank = ".$user_rank['user_rank']." " ." WHERE g.goods_id = '$goods_id'" ." AND g.is_delete = 0 limit 1";
        $goods = $Model->query($sql);
        return $goods[0];
    }

    /**
     * 获取购物车中指定商品信息
     * @param int $uid 用户ID
     * @param int $goods_id 商品ID
     * @param string $spec 商品属性
     */
    public function get_goods_info($uid,$goods_id,$spec,$act_type){
        if($act_type=='is_exchange'){
            $where=" AND giving in('1','2') ";
        }else if($act_type=='is_quota'){
            $where=" AND giving='3' ";
        }
//        促销价
        else if ($act_type == 'is_promote') {
        	$where = ' AND giving = 4';
		}
//		秒杀价
		else if ($act_type == 'is_buynow'){
        	$where = ' AND giving = 5';
		}
        else{
            $where=" AND giving='0' ";
        }
        $Model=new Model();
        $sql = "SELECT rec_id,goods_number,act_id,giving,is_check FROM " . C('DB_PREFIX') ."cart WHERE user_id = '" . $uid . "' AND goods_id = '$goods_id' " ." $where " ." AND parent_id = 0 AND goods_attr = '" . D('Goods')->get_goods_attr_info($spec) . "' " ." AND extension_code <> 'package_buy' " ." AND rec_type = '" . CART_GENERAL_GOODS . "'";

        $row = $Model->query($sql);
        return $row[0];
    }


    /**
     * 获取商品最小购买数量
     * @param int $goods_id 商品ID
     * @return int;
     */
    public function min_buy_num($goods_id){
        $min_buy_num=D('goods')->where(array('goods_id'=>$goods_id))->getField('min_buy_num');
        return $min_buy_num;
    }

    /**
     * 检验数量是否有效
     * @param $goods_id
     * @param $wid
     * @param $num
     * @return array
     */
    public function check_num_valid($goods_id,$wid,$num){

        $min_buy_num = $this->min_buy_num($goods_id);
        $arrGoods = M('goods')->field('goods_name,goods_number,extension_code,is_on_sale,is_presell')->where(array('goods_id'=>$goods_id))->find();
        if(!$arrGoods['is_on_sale']){
            return array('status'=>0,'msg'=>'商品已下架');
        }
        $arrGoods['is_presell']=(int)$arrGoods['is_presell'];

        if($arrGoods['is_presell']!=0){
            //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
            $arrGoods['is_presell']=D('Goodsstorage')->check_whether_presell($goods_id,$wid);
        }

        if($arrGoods['is_presell']==1 || empty($wid)){
            if ($arrGoods ['extensioan_code'] != 'package_buy') {
                if ($arrGoods ['goods_number'] < $num) {
                    if($num == $min_buy_num ){
                        return array('status'=>0,'msg'=>'该商品库存不足，当前无法购买');
                    }else{
                        return array('status'=>0,'msg'=>'已达当前可购买的数量');
                    }

                }
            }
        }elseif($wid){
            if(!D('Goodsstorage')->check_warehous_goods($wid,$goods_id,$num)){
                if($num == $min_buy_num ){
                    return array('status'=>0,'msg'=>'该商品库存不足，当前无法购买');
                }else{
                    return array('status'=>0,'msg'=>'已达当前可购买的数量');
                }
            }
        }

        return array('status'=>1);
    }

    /**
     * 删除购物车商品记录
     * @param int $uid 用户ID
     * @param int $rec_id 购物车记录ID
     * @return boolean
     */
    public function remove_shopping_cart_goods($uid,$rec_id){

        $res=$this->flow_drop_cart_goods($rec_id, $is_hd, $uid);
        if($res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除购物车中的商品
     *
     * @access public
     * @param integer $id
     * @param $is_hd 是否为HD请求，0为h5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_drop_cart_goods( $id, $is_hd=0, $uid = 0 ) {
        /* 取得商品id */
        $sql = "SELECT * FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id'";
        //        dd($sql);
        $Model=new Model();
        $row = $Model->query($sql);
        $row = $row[0];
        if ($row) {
            // 如果是超值礼包
            if ($row ['extension_code'] == 'package_buy') {
                $sql = "DELETE FROM " . C('DB_PREFIX'). "cart WHERE user_id = '" . $uid . "' " . "AND rec_id = '$id' LIMIT 1";
            }
            // 如果是普通商品，同时删除所有赠品及其配件
            elseif ($row ['parent_id'] == 0) {
                /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
                $sql = "SELECT c.rec_id
				FROM " . C('DB_PREFIX') . "cart AS c, " . C('DB_PREFIX') . "group_goods AS gg, " . C('DB_PREFIX') . "goods AS g
				WHERE gg.parent_id = '" . $row ['goods_id'] . "'
				AND c.goods_id = gg.goods_id
				AND c.parent_id = '" . $row ['goods_id'] . "'
				AND c.extension_code <> 'package_buy'
				AND gg.goods_id = g.goods_id
				AND g.is_alone_sale = 0";
                $res = $Model->query($sql);
                $_del_str = $id . ',';
                foreach ($res as $key=>$id_alone_sale_goods) {
                    $_del_str .= $id_alone_sale_goods ['rec_id'] . ',';
                }
                $_del_str = trim($_del_str, ',');
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id IN ($_del_str) OR parent_id = '$row[goods_id]'";
            }
            // 如果不是普通商品，只删除该商品即可
            else {
                $sql = "DELETE FROM " . C('DB_PREFIX') . "cart WHERE rec_id = '$id' LIMIT 1";
            }
            $Model->execute($sql);
        }else{
            return false;
        }
        //删除购物车中不能单独销售的商品
        $this->flow_clear_cart_alone( $is_hd, $uid );
        return true;
    }

    /**
     * 删除购物车中不能单独销售的商品
     *
     * @access public
     * @param $is_hd hd请求标志，0为H5请求；1为HD请求；
     * @param $uid 用户ID；
     * @return void
     */
    function flow_clear_cart_alone( $is_hd=0, $uid=0 ) {
        /* 查询：购物车中所有不可以单独销售的配件 */
        $sql = "SELECT c.rec_id, gg.parent_id
    		FROM " . C('DB_PREFIX') . "cart AS c
    		LEFT JOIN " . C('DB_PREFIX') . "group_goods AS gg ON c.goods_id = gg.goods_id
    		LEFT JOIN " . C('DB_PREFIX') . "goods AS g ON c.goods_id = g.goods_id
    		WHERE c.user_id = '" . $uid . "'
    		AND c.extension_code <> 'package_buy'
    		AND gg.parent_id > 0
    		AND g.is_alone_sale = 0";

        $Model=new Model();
        $res = $Model->query($sql);
        $rec_id = array();
        foreach ($res as $key=>$row) {
            $rec_id [$row ['rec_id']] [] = $row ['parent_id'];
        }
        if (empty($rec_id)) {
            return;
        }

        /* 查询：购物车中所有商品 */
        $sql = "SELECT DISTINCT goods_id
    		FROM " . C('DB_PREFIX') .
        		"cart WHERE user_id = '" . $uid . "'
    		AND extension_code <> 'package_buy'";

        $res = $Model->query($sql);
        $cart_good = array();
        foreach ($res as $key=>$row) {
            $cart_good [] = $row ['goods_id'];
        }
        if (empty($cart_good)) {
            return;
        }

        /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
        $del_rec_id = '';
        foreach ($rec_id as $key => $value) {
            foreach ($value as $v) {
                if (in_array($v, $cart_good)) {
                    continue 2;
                }
            }

            $del_rec_id = $key . ',';
        }
        $del_rec_id = trim($del_rec_id, ',');

        if ($del_rec_id == '') {
            return;
        }

        /* 删除 */

        /// HD请求处理
        $sql = "DELETE FROM " . C('DB_PREFIX') .
        "cart WHERE user_id = '" . $uid . "'
        AND rec_id IN ($del_rec_id)";

        $Model->execute($sql);
    }

    /**
     * 清空购物车
     * @param   int     $type   类型：默认普通商品
     */
    public function clear_cart($uid,$type = CART_GENERAL_GOODS,$rec_ids='') {
        $map = array('user_id'=>$uid,'rec_type'=>$type);
        if(!empty($rec_ids)){
            $where['rec_id'] = array('in',explode(',', $rec_ids));
            $where['parent_id'] = array('in',explode(',', $rec_ids));
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $res = $this->where($map)->delete();
    }

    /**
     * 检查商品是否需要传属性
     * @param int $goods_id 商品ID
     * @param string $spec 商品属性
     */
    public function check_spec($goods_id,$spec){


        // 检查：如果商品有规格，而post的数据没有规格，把商品的规格属性通过JSON传到前台
        if (empty($spec)) {
            $Model=new Model();
            $sql = "SELECT a.attr_id, a.attr_name, a.attr_type," . "g.goods_attr_id, g.attr_value, g.attr_price " . 'FROM ' . C('DB_PREFIX') . 'goods_attr AS g ' . 'LEFT JOIN ' . C('DB_PREFIX') . 'attribute AS a ON a.attr_id = g.attr_id ' . "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods_id . "' " . 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
            $res = $Model->query($sql);
            if (!empty($res)) {
                $spe_arr = array();
                foreach ($res as $key=>$row) {
                    $spe_arr [$row ['attr_id']] ['attr_type'] = $row ['attr_type'];
                    $spe_arr [$row ['attr_id']] ['name'] = $row ['attr_name'];
                    $spe_arr [$row ['attr_id']] ['attr_id'] = $row ['attr_id'];
                    $spe_arr [$row ['attr_id']] ['values'] [] = array(
                        'label' => $row ['attr_value'],
                        'price' => $row ['attr_price'],
                        'format_price' => price_format($row ['attr_price'], false),
                        'id' => $row ['goods_attr_id']
                    );
                }
                $i = 0;
                $spe_array = array();
                foreach ($spe_arr as $row) {
                    $spe_array [] = $row;
                }
                return array('status'=>0,'msg'=>$spe_array);
            }
        }
        return array('status'=>1);
    }


    /**
     * 判断 购物车指定记录 是否存在
     * @param number $uid 用户ID；
     * @param number $goods_id 商品ID；
     * @return boolean true存在；false不存在；
     * @author 43
     */
    public function is_exists_record( $uid, $goods_id,$act_id=0,$act_type="",$goods_attr_id=0) {
        $where["goods_id"] = $goods_id;
        $where["user_id"] = $uid;
       	$where["can_handsel"] = 0;
       	$where["goods_attr_id"] = $goods_attr_id;
       	if($act_type=='is_exchange'){
       	    $where["giving"]=array('in','1,2');
       	}else if($act_type=='is_quota'){
       	    $where["giving"]='3';
       	}
       	else if($act_type == 'is_promote')
		{
			$where['giving'] = '4';
		}
		else if($act_type == 'is_buynow')
		{
			$where['giving'] = '5';
		}
       	else
		{
       	    $where["giving"]='0';
       	}
  

        $info = M("Cart")->where($where)->find();

        if( !empty($info) ) {
            return $info;
        }else {
            return false;
        }
    }

    /**
     * 调用购物车信息
     *
     * @access  public
     * @param $uid 用户ID；
     * @return  string
     */
    public function insert_cart_info($uid = 0 ,$have_gift=true) {
        if(!$have_gift){
            $is_gift = " AND is_gift = 0";
        }
        $sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .' FROM ' . C('DB_PREFIX') . 'cart ' ." WHERE user_id = '" . $uid . "' AND rec_type = '" . CART_GENERAL_GOODS . "'".$is_gift;

        $Model=new Model();
        $row = $Model->query($sql);

        $row=$row[0];
        if ($row) {
            $number = intval($row['number']);
            $amount = floatval($row['amount']);
        } else {
            $number = 0;
            $amount = 0;
        }

        return array('number'=>$number,'amount'=>$amount);
        /*$str = sprintf(L('cart_info'), $number, price_format($amount, false));
    
        return '<a href="flow.php" title="' . L('view_cart') . '">' . $str . '</a>';*/
    }
    
    /**
     * 调用购物车信息2
     *
     * @access  public
     * @param $uid 用户ID；
     * @return  string
     */
    public function insert_cart_info2($uid,$wid) {
        $favourable_list = $this->favourable_list_flow($uid,$wid);
        $cart_goods = $this->get_cart_goods($uid,$wid,0,$favourable_list);

        return array('number'=>(int)$cart_goods['total']['cart_total_number'],'amount'=>(float)sprintf("%.2f",$cart_goods['total']['cart_total_amount']));
        /*$str = sprintf(L('cart_info'), $number, price_format($amount, false));
    
        return '<a href="flow.php" title="' . L('view_cart') . '">' . $str . '</a>';*/
    }
    
    

    /**
     * 获取当前购物车的商品数
     * @param	int $uid
     */
    public function get_cart_count($uid){
        $count = M('Cart')->where(array('user_id'=>$uid))->count();
        return $count;
    }




    /*
     * 限购商品购物车增减
     */
    public function change_quota_shopping_cart($act_id,$uid,$goods_id,$current_num,$num=1,$wid=0){
        $activity = D ( 'favourable_activity' );
        $cart = D('cart');
        $favourable = $activity->favourable_info($act_id);

        if (empty($favourable)) {
            returnApiError('优惠活动不存在');
        }
        /* 判断活动类型 */
        if ($favourable ['act_type'] <> 3) {
            returnApiError('活动类型不匹配！');
        }

        /* 判断活动日期是否有效 */
        $time = gmtime();
        if ($time < $favourable['_start_time'] || $time > $favourable['_end_time']) {
            returnApiError('当前活动未开始或已过期');
        }

        /* 判断用户能否享受该优惠 */
        if (! $cart->favourable_available ( $favourable, $uid )) {
            returnApiError ( '您不能享受该优惠' );
        }

        /* 检查是否选择了产品 */
        if (empty ( $goods_id )) {
            returnApiError ( '请选择限购商品' );
        }

        /* 检查产品是否有效 */
        $quota_goods = array ();
        foreach ( $favourable ['quota'] as $item ) {
            if ($item ['id'] == $goods_id) {
                $quota_goods = $item;
                break;
            }
        }

        if (empty ( $quota_goods )) {
            returnApiError ( '没有匹配的商品');
        }
        if($num>0){
            // 查询：系统启用了库存，检查输入的商品数量是否有效
            $goodsnmber=$current_num+$num;
            $arrGoods = D('goods')->field('goods_name,goods_number,extension_code,is_on_sale,is_presell')->where(array('goods_id'=>$goods_id))->find();
            if(!$arrGoods['is_on_sale']){
                returnApiError('商品已下架');
            }
            $arrGoods['is_presell']=(int)$arrGoods['is_presell'];
            if($arrGoods['is_presell']!=0){
                //检查是否该商品是否是预售商品,若是预售商品，则返回1,否则是现售返回0;
                $arrGoods['is_presell']=D('Goodsstorage')->check_whether_presell($goods_id,$wid);
            }
            if($arrGoods['is_presell']){
                if (intval(C('use_storage')) > 0 && $arrGoods ['extension_code'] != 'package_buy') {
                    if ($arrGoods ['goods_number'] < $goodsnmber) {
                        returnApiError("库存不足");
                    }
                }
            }elseif($wid){
                if(!D('Goodsstorage')->check_warehous_goods($wid,$goods_id,$goodsnmber)){
                    returnApiError('仓库商品库存不足');
                }
            }
            /* 限购类型(全局或者指定产品) */
            $count = round($favourable['act_type_ext']);
            if ($count > 0) {
                /* 检查购物车中是否已有该优惠 */
                $cart_favourable = $cart->cart_favourable_quota($act_id,'',$uid);
                if ($cart_favourable && $cart_favourable['num'] >= $count) {
                    returnApiError("此活动限购" . $count . "份，您已加入购物车" . $cart_favourable['num'] . "份");
                }
                /* 检查是否已参与过该活动 */
                $quota_favourable = $cart->activity_favourable_quota($act_id,'',$uid);
                if ($quota_favourable && $quota_favourable['num'] >= $count) {
                    returnApiError("此活动您已参与过");
                }
            } else {
                /* 检查购物车中是否已有该优惠 */
                $cart_favourable = $cart->cart_favourable_quota($act_id, $goods_id,$uid);
                if ($cart_favourable && $cart_favourable['num'] >= $quota_goods['count']) {
                    returnApiError("此产品限购'$quota_goods[count]'份，您已加入购物车" . $cart_favourable['num'] . "份");
                }
                /* 检查是否已参与过该活动 */
                $quota_favourable = $cart->activity_favourable_quota($act_id, $goods_id,$uid);
                if ($quota_favourable && $quota_favourable['num'] >= $quota_goods['count']) {
                    returnApiError("此活动您已参与过");
                }
            }
        }

        /* 修改到购物车 */
        $res = $cart->change_quota_to_cart($act_id, $quota_goods ['id'], $quota_goods ['price']*$num,$uid,$num);
    }


    /**
     * 获取分类ID/名称
     * @param string $act_range_ext 分类ID串
     */
    public function get_act_cate_info($act_range_ext){
        $Model=new Model();
        $sql = 'SELECT cat_id,cat_name FROM ' . C('DB_PREFIX') . 'category ' ." WHERE cat_id in(".$act_range_ext.") order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row;
        }else{
            return '';
        }
    }

    /**
     * 获取品牌ID\名称
     * @param string $act_range_ext 品牌ID串
     */
    public function get_act_brand_info($act_range_ext){
        $Model=new Model();
        $sql = 'SELECT brand_id,brand_name FROM ' . C('DB_PREFIX') . 'brand ' ." WHERE brand_id in(".$act_range_ext.") order by sort_order asc";
        $row = $Model->query($sql);
        if($row[0]){
            return $row;
        }else{
            return '';
        }
    }

    /**
     * 返回最新商品价格并修改
     * Created by Jerry
     * @param $goods_id
     * @param $cart_id
     * @return mixed
     */
    protected function update_cart_goods_price($goods_id, $cart_id){
        //        查询商品价格
        $goodsModel = D('Goods');
        $goods_price = $goodsModel->get_final_price($goods_id);

        $where = array(
            'rec_id'    =>  $cart_id,
        );
        $updateData = array(
            'goods_price'   =>  $goods_price,
        );
        $rs = M("cart")->where($where)->save($updateData);

        return $goods_price;
    }


    /**
     * 取得红包信息
     * @param $bonus_id 红包id
     * @param string $bonus_sn  红包序列号
     * @param int $bonus_type
     * @return bool 红包信息
     */
    public function bonus_info($bonus_id, $bonus_sn = '',$bonus_type = 0) {
        $sql = "SELECT t.*, b.* " .
            "FROM " . C('DB_PREFIX') . "bonus_type AS t," .
            C('DB_PREFIX') . "user_bonus AS b " .
            "WHERE t.type_id = b.bonus_type_id AND t.bonus_type = ".$bonus_type;
        if ($bonus_id > 0) {
            $sql .= " AND b.bonus_id = '$bonus_id'";
        } else {
            $sql .= " AND b.bonus_sn = '$bonus_sn'";
        }
        $sql .=' limit 1';
        $Model=new Model();
        $row=$Model->query($sql);
        $bouns = $row[0];
        $now = gmtime();
        if(($bouns['deadline']>0 && $bouns['deadline']<$now) || ($bouns['deadline']==0 && $bouns['use_end_date']<$now)){
            $bouns = false;
        }

        return $bouns;
    }


    /**
     * 检查购物车商品是否有价格变动
     * @param $cart_goods
     * @param $uid
     * @param $show_return
     */
    public function check_goods_price($cart_goods,$uid,$show_return=true){
        //    	dd($cart_goods);
        if(count($cart_goods)>0){
            $cart_goods_list = array();
            $have_change = false;
            $msg = '购物车中商品价格有变动';
            $user_rank = M('users')->where(array("user_id"=>$uid))->getField('user_rank');

            foreach($cart_goods as $goods){

                if($goods['is_quota']>0){
                    $res = $this->check_quota_price($goods,$uid,$goods['is_quota']);
                }
                elseif($goods['is_gift']>0)
                {
                    $res = $this->check_gift_price($goods,$uid,$goods['is_gift']);
                }
                //    			else if ($goods['giving'] == 4)
                //    			{
                //					$res = $this->check_promote_price($goods);
                //				}
                else
                {
                    $res = $this->check_normal_goods_price($goods,$uid,$user_rank);
                }

                if($res['have_change']==1){
                    $cart_goods_list[] = $res['cart_goods'];
                    $have_change = true;
                }
            }

            if($have_change && $show_return){
                returnApiError($msg,$cart_goods_list);
            }
        }
    }

    /**
     * 抢购商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $act_id
     * @return array
     */
    private function check_quota_price($goods,$uid,$act_id){
        $result = array('have_change'=>0);
        $activity = D ( 'favourable_activity' );
        if(S('favourable_'.$goods['is_quota'])){
            $favourable = S('favourable_'.$goods['is_quota']);
        }else{
            $favourable = $activity->favourable_info($goods['is_quota']);
            if(!empty($favourable)){
                S('favourable_'.$goods['is_quota'],$favourable,20);
            }
        }
        if(!empty($favourable['quota'])){
            $favourable_goods_list = $favourable['quota'];
            foreach ($favourable_goods_list as $favourable_goods){
                if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
                    $goods_price = $favourable_goods['price'];
                    D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
                    $goods['new_goods_price'] = $goods_price;
                    $result['have_change'] = 1;
                    $result['cart_goods'] = $goods;
                }
            }
        }

        return $result;
    }

    /**
     * 赠送或优惠商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $act_id
     * @return array
     */
    private function check_gift_price($goods,$uid,$act_id){
        $result = array('have_change'=>0);
        $activity = D ( 'favourable_activity' );
        if(S('favourable_'.$goods['is_gift'])){
            $favourable = S('favourable_'.$goods['is_gift']);
        }else{
            $favourable = $activity->favourable_info($goods['is_gift']);
            if(!empty($favourable)){
                S('favourable_'.$goods['is_gift'],$favourable,20);
            }
        }
        if(!empty($favourable['gift'])){
            $favourable_goods_list = $favourable['gift'];
            foreach ($favourable_goods_list as $favourable_goods){
                if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
                    if($goods['goods_price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }elseif($favourable_goods['price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }else{
                        $goods_price = $favourable_goods['price'];
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
                    }
                    $goods['new_goods_price'] = $goods_price;
                    $result['have_change'] = 1;
                    $result['cart_goods'] = $goods;
                }
            }
        }

        return $result;
    }

    /**
     * 普通商品购物车价格变动检查
     * @param $goods
     * @param $uid
     * @param $user_rank
     * @return array
     */
    private function check_normal_goods_price($goods,$uid,$user_rank){
        $result = array('have_change'=>0);
        $map = array();
        $spec = "";

        if($goods['goods_attr_id']){
            $spec = explode(',', $goods['goods_attr_id']);
        }
        $goods_price = D('Goods')->get_final_price($goods['goods_id'], $goods['goods_number'], true, $spec, $uid);
        ////		促销价
        //		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
        //		if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
        //			returnApiError('促销商品价格和数量有所变动');
        //		}



        if ($goods['giving'] > 0) {

            if ($goods['is_buynow'] == 0) {
                $promoteService = new PromoteService();
                $status = $promoteService->getPromotePriceStatus($goods);

                if ($status) {
                    $this->isPriceChange($goods, $goods_price);
                }
                else{
                    D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('giving', 0);
                }
            }
            else if($goods['is_buynow'] == 1){
                $buyNowGoodsService = new BuyNowGoodsRepository($uid);
                $status = $buyNowGoodsService->getBuyNowGoodsData($goods);
                if ($status['buy_now_status'] == 3) {
                    $this->isPriceChange($goods, $goods_price);
                }
            }
        }


        if(($goods_price - $goods['goods_price']) != 0){
            D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
            $goods['new_goods_price'] = $goods_price;
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }

    /**
     * Created by Jerry
     * @param $goods
     * @param $goods_price
     * @return bool
     */
    protected function isPriceChange($goods, $goods_price)
    {
        $promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
        if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
            returnApiError('商品价格和数量有所变动');
        }

        return true;
    }

}